{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/bitkira/Colab/blob/main/tutorial_notebooks_zh/tools.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install git+https://github.com/EvoAgentX/EvoAgentX.git"
      ],
      "metadata": {
        "id": "o91DzECfqSzt"
      },
      "id": "o91DzECfqSzt",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install PyPDF2 selenium html2text fastmcp"
      ],
      "metadata": {
        "id": "W8OzqM_yqTNS"
      },
      "id": "W8OzqM_yqTNS",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "b72e2812",
      "metadata": {
        "id": "b72e2812"
      },
      "source": [
        "# 在 EvoAgentX 中使用工具\n",
        "\n",
        "本教程将指导你使用 EvoAgentX 强大的工具生态系统。工具允许代理与外部世界交互、执行计算和访问信息。我们将涵盖：\n",
        "\n",
        "1. **理解工具架构**：了解基础 Tool 类及其功能\n",
        "2. **代码解释器**：使用 Python 和 Docker 解释器安全执行 Python 代码\n",
        "3. **搜索工具**：使用 Wikipedia 和 Google 搜索工具访问网络信息\n",
        "4. **文件操作**：处理文件操作，包括读取和写入文件，并特别支持不同的文件格式，如 PDF\n",
        "5. **浏览器自动化**：控制网页浏览器与网站和 Web 应用程序交互\n",
        "6. **MCP 工具**：使用模型上下文协议连接到外部服务\n",
        "\n",
        "通过本教程，你将了解如何在自己的代理和工作流中利用这些工具。\n",
        "\n",
        "---\n",
        "\n",
        "## 1. 理解工具架构\n",
        "\n",
        "EvoAgentX 工具生态系统的核心是 `Tool` 基类，它为所有工具提供了标准化接口。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "32930d09",
      "metadata": {
        "id": "32930d09"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.tool import Tool"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "49fbdb39",
      "metadata": {
        "id": "49fbdb39"
      },
      "source": [
        "\n",
        "`Tool` 类实现了三个关键方法：\n",
        "\n",
        "- `get_tool_schemas()`：返回工具的 OpenAI 兼容函数模式\n",
        "- `get_tools()`：返回工具提供的可调用函数列表\n",
        "- `get_tool_descriptions()`：返回工具功能描述\n",
        "\n",
        "EvoAgentX 中的所有工具都继承自这个基类，确保代理使用它们时有一致的接口。\n",
        "\n",
        "### 关键概念\n",
        "\n",
        "- **工具集成**：工具通过函数调用协议与代理无缝集成\n",
        "- **模式**：每个工具都提供描述其功能、参数和输出的模式\n",
        "- **模块化**：工具可以轻松添加到任何支持函数调用的代理中\n",
        "\n",
        "---\n",
        "\n",
        "## 2. 代码解释器\n",
        "\n",
        "EvoAgentX 提供两种主要的代码解释器工具：\n",
        "\n",
        "1. **PythonInterpreter**：在受控环境中执行 Python 代码\n",
        "2. **DockerInterpreter**：在隔离的 Docker 容器中执行代码\n",
        "\n",
        "### 2.1 PythonInterpreter\n",
        "\n",
        "**PythonInterpreter 提供了一个安全的环境来执行 Python 代码，可以精细控制导入、目录访问和执行上下文。它使用沙箱方法来限制潜在的有害操作。**\n",
        "\n",
        "#### 2.1.1 设置\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "c94bd91f",
      "metadata": {
        "id": "c94bd91f"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.interpreter_python import PythonInterpreter\n",
        "\n",
        "# 使用特定的允许导入和目录访问进行初始化\n",
        "interpreter = PythonInterpreter(\n",
        "    project_path=\".\",  # 默认为当前目录\n",
        "    directory_names=[\"examples\", \"evoagentx\"],\n",
        "    allowed_imports={\"os\", \"sys\", \"math\", \"random\", \"datetime\"}\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d539c257",
      "metadata": {
        "id": "d539c257"
      },
      "source": [
        "\n",
        "#### 2.1.2 可用方法\n",
        "\n",
        "`PythonInterpreter` 提供以下可调用方法：\n",
        "\n",
        "##### 方法 1: execute(code, language)\n",
        "\n",
        "**描述**：在安全环境中直接执行 Python 代码。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "cef1cbf8",
      "metadata": {
        "id": "cef1cbf8"
      },
      "outputs": [],
      "source": [
        "# 执行简单的代码片段\n",
        "result = interpreter.execute(\"\"\"\n",
        "print(\"Hello, World!\")\n",
        "import math\n",
        "print(f\"The value of pi is: {math.pi:.4f}\")\n",
        "\"\"\", \"python\")\n",
        "\n",
        "print(result)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "750cd8f5",
      "metadata": {
        "id": "750cd8f5"
      },
      "source": [
        "\n",
        "**返回类型**：`str`\n",
        "\n",
        "**示例返回**："
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "Hello, World!\n",
        "The value of pi is: 3.1416"
      ],
      "metadata": {
        "id": "vDGcpR8ruqXY"
      },
      "id": "vDGcpR8ruqXY",
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "116fac22",
      "metadata": {
        "id": "116fac22"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 2: execute_script(file_path, language)\n",
        "\n",
        "**描述**：在安全环境中执行 Python 脚本文件。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "2a068c3d",
      "metadata": {
        "id": "2a068c3d"
      },
      "outputs": [],
      "source": [
        "# 执行 Python 脚本文件\n",
        "script_path = \"examples/hello_world.py\"\n",
        "script_result = interpreter.execute_script(script_path, \"python\")\n",
        "print(script_result)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e8345930",
      "metadata": {
        "id": "e8345930"
      },
      "source": [
        "\n",
        "**返回类型**：`str`\n",
        "\n",
        "**示例返回**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "decf23cc",
      "metadata": {
        "id": "decf23cc"
      },
      "outputs": [],
      "source": [
        "Running hello_world.py...\n",
        "Hello from the script file!\n",
        "Script execution completed."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e3f41c0c",
      "metadata": {
        "id": "e3f41c0c"
      },
      "source": [
        "\n",
        "#### 2.1.3 设置提示\n",
        "\n",
        "- **项目路径**：`project_path` 参数应指向项目的根目录，以确保正确的文件访问。默认为当前目录（\".\"）。\n",
        "\n",
        "- **目录名称**：`directory_names` 列表指定项目中可以导入的目录。这对安全性很重要，可以防止未授权的访问。默认为空列表 `[]`。\n",
        "\n",
        "- **允许的导入**：`allowed_imports` 集合限制可以在执行代码中导入的 Python 模块。默认为空列表 `[]`。\n",
        "  - **重要**：如果 `allowed_imports` 设置为空列表，则不应用导入限制。\n",
        "  - 指定时，只添加你认为安全的模块：\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "edeb1c7e",
      "metadata": {
        "id": "edeb1c7e"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "# 带有导入限制的示例\n",
        "interpreter = PythonInterpreter(\n",
        "    project_path=os.getcwd(),\n",
        "    directory_names=[\"examples\", \"evoagentx\", \"tests\"],\n",
        "    allowed_imports={\n",
        "        \"os\", \"sys\", \"time\", \"datetime\", \"math\", \"random\",\n",
        "        \"json\", \"csv\", \"re\", \"collections\", \"itertools\"\n",
        "    }\n",
        ")\n",
        "\n",
        "# 无导入限制的示例\n",
        "interpreter = PythonInterpreter(\n",
        "    project_path=os.getcwd(),\n",
        "    directory_names=[\"examples\", \"evoagentx\"],\n",
        "    allowed_imports=[]  # 允许导入任何模块\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a49c29b4",
      "metadata": {
        "id": "a49c29b4"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "### 2.2 DockerInterpreter\n",
        "\n",
        "**DockerInterpreter 在隔离的 Docker 容器中执行代码，提供最大的安全性和环境隔离。它允许安全执行潜在风险的代码，具有自定义环境、依赖项和完整的资源隔离。使用此工具需要在你的机器上安装并运行 Docker。**\n",
        "\n",
        "#### 2.2.1 设置\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "3288e411",
      "metadata": {
        "id": "3288e411"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.interpreter_docker import DockerInterpreter\n",
        "\n",
        "# 使用特定的 Docker 镜像初始化\n",
        "interpreter = DockerInterpreter(\n",
        "    image_tag=\"fundingsocietiesdocker/python3.9-slim\",\n",
        "    print_stdout=True,\n",
        "    print_stderr=True,\n",
        "    container_directory=\"/app\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0e01dce8",
      "metadata": {
        "id": "0e01dce8"
      },
      "source": [
        "\n",
        "#### 2.2.2 可用方法\n",
        "\n",
        "`DockerInterpreter` 提供以下可调用方法：\n",
        "\n",
        "##### 方法 1: execute(code, language)\n",
        "\n",
        "**描述**：在 Docker 容器内执行代码。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "766ce8ad",
      "metadata": {
        "id": "766ce8ad"
      },
      "outputs": [],
      "source": [
        "# 在 Docker 容器中执行 Python 代码\n",
        "result = interpreter.execute(\"\"\"\n",
        "import platform\n",
        "print(f\"Python version: {platform.python_version()}\")\n",
        "print(f\"Platform: {platform.system()} {platform.release()}\")\n",
        "\"\"\", \"python\")\n",
        "\n",
        "print(result)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d5331966",
      "metadata": {
        "id": "d5331966"
      },
      "source": [
        "\n",
        "**返回类型**：`str`\n",
        "\n",
        "**示例返回**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "fe9b8e84",
      "metadata": {
        "id": "fe9b8e84"
      },
      "outputs": [],
      "source": [
        "Python version: 3.9.16\n",
        "Platform: Linux 5.15.0-1031-azure"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "50d20ef9",
      "metadata": {
        "id": "50d20ef9"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 2: execute_script(file_path, language)\n",
        "\n",
        "**描述**：在 Docker 容器内执行脚本文件。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "8847604d",
      "metadata": {
        "id": "8847604d"
      },
      "outputs": [],
      "source": [
        "# 在 Docker 中执行 Python 脚本文件\n",
        "script_path = \"examples/docker_test.py\"\n",
        "script_result = interpreter.execute_script(script_path, \"python\")\n",
        "print(script_result)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "337813b6",
      "metadata": {
        "id": "337813b6"
      },
      "source": [
        "\n",
        "**返回类型**：`str`\n",
        "\n",
        "**示例返回**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "43497d3e",
      "metadata": {
        "id": "43497d3e"
      },
      "outputs": [],
      "source": [
        "Running container with script: /app/script_12345.py\n",
        "Hello from the Docker container!\n",
        "Container execution completed."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f30ed181",
      "metadata": {
        "id": "f30ed181"
      },
      "source": [
        "\n",
        "#### 2.2.3 设置提示\n",
        "\n",
        "- **Docker 要求**：使用此解释器前，确保 Docker 已安装并在系统上运行。\n",
        "\n",
        "- **镜像管理**：你需要提供 `image_tag` **或** `dockerfile_path` 中的一个，不能同时提供：\n",
        "  - **选项 1：使用现有镜像**\n",
        "    ```python\n",
        "    interpreter = DockerInterpreter(\n",
        "        image_tag=\"python:3.9-slim\",  # 使用现有的 Docker Hub 镜像\n",
        "        container_directory=\"/app\"\n",
        "    )\n",
        "    ```\n",
        "  \n",
        "  - **选项 2：从 Dockerfile 构建**\n",
        "    ```python\n",
        "    interpreter = DockerInterpreter(\n",
        "        dockerfile_path=\"path/to/Dockerfile\",  # 构建自定义镜像\n",
        "        image_tag=\"my-custom-image-name\",      # 构建镜像的名称\n",
        "        container_directory=\"/app\"\n",
        "    )\n",
        "    ```\n",
        "\n",
        "- **文件访问**：\n",
        "  - 要使本地文件在容器中可用，使用 `host_directory` 参数：\n",
        "  ```python\n",
        "  interpreter = DockerInterpreter(\n",
        "      image_tag=\"python:3.9-slim\",\n",
        "      host_directory=\"/path/to/local/files\",\n",
        "      container_directory=\"/app/data\"\n",
        "  )\n",
        "  ```\n",
        "  - 这将本地目录挂载到指定的容器目录，使所有文件可访问。\n",
        "\n",
        "- **容器生命周期**：\n",
        "  - Docker 容器在初始化解释器时创建，在解释器销毁时移除。\n",
        "  - 对于长时间运行的会话，可以设置 `print_stdout` 和 `print_stderr` 以查看实时输出。\n",
        "\n",
        "- **故障排除**：\n",
        "  - 如果遇到权限问题，确保你的用户具有 Docker 权限。\n",
        "  - 对于网络相关错误，检查 Docker 守护进程是否有适当的网络访问权限。\n",
        "\n",
        "---\n",
        "\n",
        "## 3. 搜索工具\n",
        "\n",
        "EvoAgentX 提供多种搜索工具来从各种来源检索信息：\n",
        "\n",
        "1. **SearchWiki**：搜索 Wikipedia 获取信息\n",
        "2. **SearchGoogle**：使用官方 API 搜索 Google\n",
        "3. **SearchGoogleFree**：无需 API 密钥即可搜索 Google\n",
        "\n",
        "### 3.1 SearchWiki\n",
        "\n",
        "**SearchWiki 工具从 Wikipedia 文章检索信息，提供摘要、完整内容和元数据。它提供了一种简单的方法，无需复杂的 API 设置即可将百科全书知识整合到你的代理中。**\n",
        "\n",
        "#### 3.1.1 设置\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "41746c35",
      "metadata": {
        "id": "41746c35"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.search_wiki import SearchWiki\n",
        "\n",
        "# 使用自定义参数初始化\n",
        "wiki_search = SearchWiki(max_sentences=3)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "12ba8b05",
      "metadata": {
        "id": "12ba8b05"
      },
      "source": [
        "\n",
        "#### 3.1.2 可用方法\n",
        "\n",
        "`SearchWiki` 提供以下可调用方法：\n",
        "\n",
        "##### 方法: search(query)\n",
        "\n",
        "**描述**：搜索 Wikipedia 获取与查询匹配的文章。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "543f38b5",
      "metadata": {
        "id": "543f38b5"
      },
      "outputs": [],
      "source": [
        "# 搜索 Wikipedia 获取信息\n",
        "results = wiki_search.search(\n",
        "    query=\"artificial intelligence agent architecture\"\n",
        ")\n",
        "\n",
        "# 处理结果\n",
        "for i, result in enumerate(results.get(\"results\", [])):\n",
        "    print(f\"结果 {i+1}: {result['title']}\")\n",
        "    print(f\"摘要: {result['summary']}\")\n",
        "    print(f\"URL: {result['url']}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "cd718d91",
      "metadata": {
        "id": "cd718d91"
      },
      "source": [
        "\n",
        "**返回类型**：`dict`\n",
        "\n",
        "**示例返回**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "d7d69911",
      "metadata": {
        "id": "d7d69911"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"results\": [\n",
        "        {\n",
        "            \"title\": \"Artificial intelligence\",\n",
        "            \"summary\": \"Artificial intelligence (AI) is the intelligence of machines or software, as opposed to the intelligence of humans or animals. AI applications include advanced web search engines, recommendation systems, voice assistants...\",\n",
        "            \"url\": \"https://en.wikipedia.org/wiki/Artificial_intelligence\"\n",
        "        },\n",
        "        {\n",
        "            \"title\": \"Intelligent agent\",\n",
        "            \"summary\": \"In artificial intelligence, an intelligent agent (IA) is anything which can perceive its environment, process those perceptions, and respond in pursuit of its own goals...\",\n",
        "            \"url\": \"https://en.wikipedia.org/wiki/Intelligent_agent\"\n",
        "        }\n",
        "    ]\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4a460091",
      "metadata": {
        "id": "4a460091"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "### 3.2 SearchGoogle\n",
        "\n",
        "**SearchGoogle 工具通过 Google 的官方自定义搜索 API 实现网络搜索，提供高质量搜索结果和内容提取。它需要 API 凭证，但提供更可靠和全面的搜索功能。**\n",
        "\n",
        "#### 3.2.1 设置\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "0e27de45",
      "metadata": {
        "id": "0e27de45"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.search_google import SearchGoogle\n",
        "\n",
        "# 使用自定义参数初始化\n",
        "google_search = SearchGoogle(\n",
        "    num_search_pages=3,\n",
        "    max_content_words=200\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4fce6c4a",
      "metadata": {
        "id": "4fce6c4a"
      },
      "source": [
        "\n",
        "#### 3.2.2 可用方法\n",
        "\n",
        "`SearchGoogle` 提供以下可调用方法：\n",
        "\n",
        "##### 方法: search(query)\n",
        "\n",
        "**描述**：搜索 Google 获取与查询匹配的内容。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "e52d8d12",
      "metadata": {
        "id": "e52d8d12"
      },
      "outputs": [],
      "source": [
        "# 搜索 Google 获取信息\n",
        "results = google_search.search(\n",
        "    query=\"evolutionary algorithms for neural networks\"\n",
        ")\n",
        "\n",
        "# 处理结果\n",
        "for i, result in enumerate(results.get(\"results\", [])):\n",
        "    print(f\"结果 {i+1}: {result['title']}\")\n",
        "    print(f\"URL: {result['url']}\")\n",
        "    print(f\"内容: {result['content'][:150]}...\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c1acbd8e",
      "metadata": {
        "id": "c1acbd8e"
      },
      "source": [
        "\n",
        "**返回类型**：`dict`\n",
        "\n",
        "**示例返回**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "10789e17",
      "metadata": {
        "id": "10789e17"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"results\": [\n",
        "        {\n",
        "            \"title\": \"Evolutionary Algorithms for Neural Networks - A Systematic Review\",\n",
        "            \"url\": \"https://example.com/paper1\",\n",
        "            \"content\": \"This paper provides a comprehensive review of evolutionary algorithms applied to neural network optimization. Key approaches include genetic algorithms, particle swarm optimization, and differential evolution...\"\n",
        "        },\n",
        "        {\n",
        "            \"title\": \"Applying Genetic Algorithms to Neural Network Training\",\n",
        "            \"url\": \"https://example.com/article2\",\n",
        "            \"content\": \"Genetic algorithms offer a powerful approach to optimizing neural network architectures and weights. This article explores how evolutionary computation can overcome limitations of gradient-based methods...\"\n",
        "        }\n",
        "    ]\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2f0a2b29",
      "metadata": {
        "id": "2f0a2b29"
      },
      "source": [
        "\n",
        "#### 3.2.3 设置提示\n",
        "\n",
        "- **API 要求**：此工具需要 Google 自定义搜索 API 凭证。在你的环境中设置它们：\n",
        "  ```python\n",
        "  # 在你的 .env 文件或环境变量中\n",
        "  GOOGLE_API_KEY=your_google_api_key_here\n",
        "  GOOGLE_SEARCH_ENGINE_ID=your_search_engine_id_here\n",
        "  ```\n",
        "\n",
        "- **获取凭证**：\n",
        "  1. 在 [Google Cloud Console](https://console.cloud.google.com/) 创建项目\n",
        "  2. 启用自定义搜索 API\n",
        "  3. 创建 API 凭证\n",
        "  4. 在 [https://cse.google.com/cse/](https://cse.google.com/cse/) 设置自定义搜索引擎\n",
        "\n",
        "---\n",
        "\n",
        "### 3.3 SearchGoogleFree\n",
        "\n",
        "**SearchGoogleFree 工具提供网络搜索功能，无需任何 API 密钥或认证。它提供了官方 Google API 的更简单替代方案，具有适合大多数一般查询的基本搜索结果。**\n",
        "\n",
        "#### 3.3.1 设置\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a1574123",
      "metadata": {
        "id": "a1574123"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.search_google_f import SearchGoogleFree\n",
        "\n",
        "# 初始化免费 Google 搜索\n",
        "google_free = SearchGoogleFree(\n",
        "    num_search_pages=3,\n",
        "    max_content_words=500\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "57d55551",
      "metadata": {
        "id": "57d55551"
      },
      "source": [
        "\n",
        "#### 3.3.2 可用方法\n",
        "\n",
        "`SearchGoogleFree` 提供以下可调用方法：\n",
        "\n",
        "##### 方法: search(query)\n",
        "\n",
        "**描述**：无需 API 密钥即可搜索 Google 获取与查询匹配的内容。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "95134fc4",
      "metadata": {
        "id": "95134fc4"
      },
      "outputs": [],
      "source": [
        "# 无需 API 密钥搜索 Google\n",
        "results = google_free.search(\n",
        "    query=\"reinforcement learning algorithms\"\n",
        ")\n",
        "\n",
        "# 处理结果\n",
        "for i, result in enumerate(results.get(\"results\", [])):\n",
        "    print(f\"结果 {i+1}: {result['title']}\")\n",
        "    print(f\"URL: {result['url']}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ddfa08b8",
      "metadata": {
        "id": "ddfa08b8"
      },
      "source": [
        "\n",
        "**返回类型**：`dict`\n",
        "\n",
        "**示例返回**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "62f3629a",
      "metadata": {
        "id": "62f3629a"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"results\": [\n",
        "        {\n",
        "            \"title\": \"Introduction to Reinforcement Learning Algorithms\",\n",
        "            \"url\": \"https://example.com/intro-rl\",\n",
        "            \"snippet\": \"A comprehensive overview of reinforcement learning algorithms including Q-learning, SARSA, and policy gradient methods.\"\n",
        "        },\n",
        "        {\n",
        "            \"title\": \"Top 10 Reinforcement Learning Algorithms for Beginners\",\n",
        "            \"url\": \"https://example.com/top-rl\",\n",
        "            \"snippet\": \"Learn about the most commonly used reinforcement learning algorithms with practical examples and implementation tips.\"\n",
        "        }\n",
        "    ]\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2acda5c5",
      "metadata": {
        "id": "2acda5c5"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "## 4. 文件操作\n",
        "\n",
        "EvoAgentX 通过个别文件工具和统一的 FileToolkit 提供全面的文件处理功能。这些工具支持文本文件的标准文件操作，并使用 PyPDF2 为 PDF 等格式提供专门的处理器。\n",
        "\n",
        "### 4.1 文件工具\n",
        "\n",
        "**EvoAgentX 通过个别文件工具和统一的 FileToolkit 提供全面的文件处理功能。这些工具支持文本文件的标准文件操作，并使用 PyPDF2 为 PDF 等格式提供专门的处理器。**\n",
        "\n",
        "#### 4.1.1 FileToolkit 使用（推荐）\n",
        "\n",
        "`FileToolkit` 提供了访问所有文件相关工具的便捷方式：\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "3ace484f",
      "metadata": {
        "id": "3ace484f"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.file_tool import FileToolkit\n",
        "\n",
        "# 初始化文件工具包\n",
        "file_Toolkit = FileToolkit()\n",
        "\n",
        "# 获取所有可用工具/方法\n",
        "available_tools = file_Toolkit.get_tools()\n",
        "print(f\"可用方法: {[tool.name for tool in available_tools]}\")\n",
        "# 输出: ['read_file', 'write_file', 'append_file']\n",
        "\n",
        "# 从工具包中获取单个工具\n",
        "read_tool = file_Toolkit.get_tool(\"read_file\")\n",
        "write_tool = file_Toolkit.get_tool(\"write_file\")\n",
        "append_tool = file_Toolkit.get_tool(\"append_file\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5840ef00",
      "metadata": {
        "id": "5840ef00"
      },
      "source": [
        "\n",
        "#### 4.1.2 可用方法\n",
        "\n",
        "`FileToolkit` 通过 `get_tool()` 提供**3个可调用方法**：\n",
        "\n",
        "##### 方法 1: read_file(file_path)\n",
        "\n",
        "**描述**: 读取文件内容，对 PDF 等不同文件类型提供特殊处理。\n",
        "\n",
        "**使用示例**:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a8f8f990",
      "metadata": {
        "id": "a8f8f990"
      },
      "outputs": [],
      "source": [
        "# 读取文本文件\n",
        "read_tool = file_Toolkit.get_tool(\"read_file\")\n",
        "text_result = read_tool(file_path=\"examples/sample.txt\")\n",
        "print(text_result)\n",
        "\n",
        "# 读取 PDF 文件（通过扩展名自动检测）\n",
        "pdf_result = read_tool(file_path=\"examples/document.pdf\")\n",
        "print(pdf_result)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5953214e",
      "metadata": {
        "id": "5953214e"
      },
      "source": [
        "\n",
        "**参数**:\n",
        "- `file_path` (str): 要读取的文件路径\n",
        "\n",
        "**返回类型**: `Dict[str, Any]`\n",
        "\n",
        "**示例返回**:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "c0abaa36",
      "metadata": {
        "id": "c0abaa36"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"success\": True,\n",
        "    \"content\": \"文件内容...\",\n",
        "    \"file_path\": \"examples/sample.txt\",\n",
        "    \"file_type\": \"text\"\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0f8546a8",
      "metadata": {
        "id": "0f8546a8"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 2: write_file(file_path, content)\n",
        "\n",
        "**描述**: 向文件写入内容，对 PDF 等不同文件类型提供特殊处理。\n",
        "\n",
        "**使用示例**:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "f1813784",
      "metadata": {
        "id": "f1813784"
      },
      "outputs": [],
      "source": [
        "# 写入文本文件\n",
        "write_tool = file_Toolkit.get_tool(\"write_file\")\n",
        "text_result = write_tool(\n",
        "    file_path=\"examples/output.txt\",\n",
        "    content=\"这是文件的新内容。\"\n",
        ")\n",
        "\n",
        "# 写入 PDF 文件（创建基本 PDF）\n",
        "pdf_result = write_tool(\n",
        "    file_path=\"examples/new_document.pdf\",\n",
        "    content=\"这个内容将出现在 PDF 中。\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b580afb9",
      "metadata": {
        "id": "b580afb9"
      },
      "source": [
        "\n",
        "**参数**:\n",
        "- `file_path` (str): 要写入的文件路径\n",
        "- `content` (str): 要写入文件的内容\n",
        "\n",
        "**返回类型**: `Dict[str, Any]`\n",
        "\n",
        "**示例返回**:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "94a60947",
      "metadata": {
        "id": "94a60947"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"success\": True,\n",
        "    \"message\": \"内容已写入 examples/output.txt\",\n",
        "    \"file_path\": \"examples/output.txt\"\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6b40a44f",
      "metadata": {
        "id": "6b40a44f"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 3: append_file(file_path, content)\n",
        "\n",
        "**描述**: 向文件追加内容，对 PDF 等不同文件类型提供特殊处理。\n",
        "\n",
        "**使用示例**:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "53ec31c5",
      "metadata": {
        "id": "53ec31c5"
      },
      "outputs": [],
      "source": [
        "# 追加到文本文件\n",
        "append_tool = file_Toolkit.get_tool(\"append_file\")\n",
        "result = append_tool(\n",
        "    file_path=\"examples/log.txt\",\n",
        "    content=\"\\n新日志条目：操作已完成。\"\n",
        ")\n",
        "print(result)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6b8582b3",
      "metadata": {
        "id": "6b8582b3"
      },
      "source": [
        "\n",
        "**参数**:\n",
        "- `file_path` (str): 要追加内容的文件路径\n",
        "- `content` (str): 要追加到文件的内容\n",
        "\n",
        "**返回类型**: `Dict[str, Any]`\n",
        "\n",
        "**示例返回**:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "bc8de27b",
      "metadata": {
        "id": "bc8de27b"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"success\": True,\n",
        "    \"message\": \"内容已追加到 examples/log.txt\",\n",
        "    \"file_path\": \"examples/log.txt\"\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1e345553",
      "metadata": {
        "id": "1e345553"
      },
      "source": [
        "\n",
        "#### 4.1.3 直接工具使用（可选）\n",
        "\n",
        "您也可以导入并直接使用个别文件工具：\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a0d9891e",
      "metadata": {
        "id": "a0d9891e"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.file_tool import ReadFileTool, WriteFileTool, AppendFileTool, FileToolBase\n",
        "\n",
        "# 为特殊格式处理创建共享文件基础\n",
        "file_base = FileToolBase()\n",
        "\n",
        "# 创建单个工具\n",
        "read_tool = ReadFileTool(file_base=file_base)\n",
        "write_tool = WriteFileTool(file_base=file_base)\n",
        "append_tool = AppendFileTool(file_base=file_base)\n",
        "\n",
        "# 直接使用工具\n",
        "result = read_tool(file_path=\"example.txt\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "84ae68c6",
      "metadata": {
        "id": "84ae68c6"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "## 5. 浏览器自动化\n",
        "\n",
        "EvoAgentX 通过 `BrowserToolkit` 类和单独的浏览器工具类提供全面的浏览器自动化功能。这些工具允许代理控制网络浏览器、导航页面、与元素交互以及提取信息。\n",
        "\n",
        "### 5.1 浏览器工具\n",
        "\n",
        "**EvoAgentX 通过 `BrowserToolkit` 类和单独的浏览器工具类提供全面的浏览器自动化功能。这些工具允许代理控制网络浏览器、导航页面、与元素交互以及提取信息。**\n",
        "\n",
        "#### 5.1.1 BrowserToolkit 使用（推荐）\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "fa75dba6",
      "metadata": {
        "id": "fa75dba6"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools import BrowserToolkit\n",
        "\n",
        "# 初始化浏览器工具包\n",
        "Toolkit = BrowserToolkit(\n",
        "    browser_type=\"chrome\",  # 选项：\"chrome\"、\"firefox\"、\"safari\"、\"edge\"\n",
        "    headless=False,         # 设置为 True 进行后台操作\n",
        "    timeout=10              # 默认超时时间（秒）\n",
        ")\n",
        "\n",
        "# 获取特定工具\n",
        "initialize_tool = Toolkit.get_tool(\"initialize_browser\")\n",
        "navigate_tool = Toolkit.get_tool(\"navigate_to_url\")\n",
        "input_tool = Toolkit.get_tool(\"input_text\")\n",
        "click_tool = Toolkit.get_tool(\"browser_click\")\n",
        "snapshot_tool = Toolkit.get_tool(\"browser_snapshot\")\n",
        "console_tool = Toolkit.get_tool(\"browser_console_messages\")\n",
        "close_tool = Toolkit.get_tool(\"close_browser\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e73bf1f6",
      "metadata": {
        "id": "e73bf1f6"
      },
      "source": [
        "\n",
        "#### 5.1.2 可用方法\n",
        "\n",
        "`BrowserToolkit` 通过 `get_tool()` 提供**7个可调用方法**：\n",
        "\n",
        "##### 方法 1: initialize_browser()\n",
        "\n",
        "启动或重启浏览器会话。必须在任何其他浏览器操作之前调用。\n",
        "\n",
        "**参数：**\n",
        "- 无需参数\n",
        "\n",
        "**示例返回：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "4e788899",
      "metadata": {
        "id": "4e788899"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"status\": \"success\",\n",
        "    \"message\": \"Browser chrome initialized successfully\"\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "fb274cfa",
      "metadata": {
        "id": "fb274cfa"
      },
      "source": [
        "\n",
        "**使用方法：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "e460820e",
      "metadata": {
        "id": "e460820e"
      },
      "outputs": [],
      "source": [
        "# 使用Toolkit\n",
        "result = Toolkit.get_tool(\"initialize_browser\")()\n",
        "\n",
        "# 直接使用 BrowserTool\n",
        "result = browser.initialize_browser()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f8715f11",
      "metadata": {
        "id": "f8715f11"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 2: navigate_to_url(url, timeout=None)\n",
        "\n",
        "导航到 URL 并自动捕获所有页面元素的快照以进行交互。\n",
        "\n",
        "**参数：**\n",
        "- `url`（str，必需）：完整的带协议的 URL（例如，\"https://example.com\"）\n",
        "- `timeout`（int，可选）：自定义超时时间（秒）\n",
        "\n",
        "**示例返回：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "8d506466",
      "metadata": {
        "id": "8d506466"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"status\": \"success\",\n",
        "    \"title\": \"Example Domain\",\n",
        "    \"url\": \"https://example.com\",\n",
        "    \"accessibility_tree\": {...},  # 完整页面结构\n",
        "    \"page_content\": \"Example Domain\\n\\nThis domain is for use in illustrative examples...\",\n",
        "    \"interactive_elements\": [\n",
        "        {\n",
        "            \"id\": \"e0\",\n",
        "            \"description\": \"More information.../link\",\n",
        "            \"purpose\": \"link\",\n",
        "            \"label\": \"More information...\",\n",
        "            \"category\": \"navigation\",\n",
        "            \"isPrimary\": False,\n",
        "            \"visible\": True,\n",
        "            \"interactable\": True\n",
        "        }\n",
        "    ]\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "80bae2fc",
      "metadata": {
        "id": "80bae2fc"
      },
      "source": [
        "\n",
        "**使用方法：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "d5cf4165",
      "metadata": {
        "id": "d5cf4165"
      },
      "outputs": [],
      "source": [
        "# 使用Toolkit\n",
        "result = Toolkit.get_tool(\"navigate_to_url\")(url=\"https://example.com\")\n",
        "\n",
        "# 直接使用 BrowserTool\n",
        "result = browser.navigate_to_url(\"https://example.com\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "28f1be18",
      "metadata": {
        "id": "28f1be18"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 3: input_text(element, ref, text, submit=False, slowly=True)\n",
        "\n",
        "使用快照中的元素引用向表单字段、搜索框或其他输入元素中输入文本。\n",
        "\n",
        "**参数：**\n",
        "- `element`（str，必需）：人类可读的描述（例如，\"搜索字段\"、\"用户名输入\"）\n",
        "- `ref`（str，必需）：快照中的元素 ID（例如，\"e0\"、\"e1\"、\"e2\"）\n",
        "- `text`（str，必需）：要输入的文本\n",
        "- `submit`（bool，可选）：输入后按回车键（默认：False）\n",
        "- `slowly`（bool，可选）：逐字符输入以触发 JS 事件（默认：True）\n",
        "\n",
        "**示例返回：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "27d1a978",
      "metadata": {
        "id": "27d1a978"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"status\": \"success\",\n",
        "    \"message\": \"Successfully input text into Search field and submitted\",\n",
        "    \"element\": \"Search field\",\n",
        "    \"text\": \"python tutorial\"\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2ae26fd9",
      "metadata": {
        "id": "2ae26fd9"
      },
      "source": [
        "\n",
        "**使用方法：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "bc12929d",
      "metadata": {
        "id": "bc12929d"
      },
      "outputs": [],
      "source": [
        "# 使用Toolkit\n",
        "result = Toolkit.get_tool(\"input_text\")(\n",
        "    element=\"搜索字段\",\n",
        "    ref=\"e1\",\n",
        "    text=\"python 教程\",\n",
        "    submit=True\n",
        ")\n",
        "\n",
        "# 直接使用 BrowserTool\n",
        "result = browser.input_text(\n",
        "    element=\"搜索字段\",\n",
        "    ref=\"e1\",\n",
        "    text=\"python 教程\",\n",
        "    submit=True\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4c373152",
      "metadata": {
        "id": "4c373152"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 4: browser_click(element, ref)\n",
        "\n",
        "使用快照中的元素引用点击按钮、链接或其他可点击元素。\n",
        "\n",
        "**参数：**\n",
        "- `element`（str，必需）：人类可读的描述（例如，\"登录按钮\"、\"下一页链接\"）\n",
        "- `ref`（str，必需）：快照中的元素 ID（例如，\"e0\"、\"e1\"、\"e2\"）\n",
        "\n",
        "**示例返回：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "4c3e6387",
      "metadata": {
        "id": "4c3e6387"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"status\": \"success\",\n",
        "    \"message\": \"Successfully clicked Login button\",\n",
        "    \"element\": \"Login button\",\n",
        "    \"new_url\": \"https://example.com/dashboard\"  # 如果发生了导航\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e66af53a",
      "metadata": {
        "id": "e66af53a"
      },
      "source": [
        "\n",
        "**使用方法：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "f58378c4",
      "metadata": {
        "id": "f58378c4"
      },
      "outputs": [],
      "source": [
        "# 使用Toolkit\n",
        "result = Toolkit.get_tool(\"browser_click\")(\n",
        "    element=\"登录按钮\",\n",
        "    ref=\"e3\"\n",
        ")\n",
        "\n",
        "# 直接使用 BrowserTool\n",
        "result = browser.browser_click(element=\"登录按钮\", ref=\"e3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3228b611",
      "metadata": {
        "id": "3228b611"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 5: browser_snapshot()\n",
        "\n",
        "捕获当前页面状态的新快照，包括所有交互元素。在不是由导航或点击引起的页面更改后使用此功能。\n",
        "\n",
        "**参数：**\n",
        "- 无需参数\n",
        "\n",
        "**示例返回：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "0e1c7800",
      "metadata": {
        "id": "0e1c7800"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"status\": \"success\",\n",
        "    \"title\": \"Search Results - Example\",\n",
        "    \"url\": \"https://example.com/search?q=python\",\n",
        "    \"accessibility_tree\": {...},  # 完整页面结构\n",
        "    \"page_content\": \"Search Results\\n\\nResult 1: Python Tutorial...\",\n",
        "    \"interactive_elements\": [\n",
        "        {\n",
        "            \"id\": \"e0\",\n",
        "            \"description\": \"search/search box\",\n",
        "            \"purpose\": \"search box\",\n",
        "            \"label\": \"Search\",\n",
        "            \"category\": \"search\",\n",
        "            \"isPrimary\": True,\n",
        "            \"visible\": True,\n",
        "            \"editable\": True\n",
        "        },\n",
        "        {\n",
        "            \"id\": \"e1\",\n",
        "            \"description\": \"Search/submit button\",\n",
        "            \"purpose\": \"submit button\",\n",
        "            \"label\": \"Search\",\n",
        "            \"category\": \"action\",\n",
        "            \"isPrimary\": True,\n",
        "            \"visible\": True,\n",
        "            \"interactable\": True\n",
        "        }\n",
        "    ]\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8eb3e989",
      "metadata": {
        "id": "8eb3e989"
      },
      "source": [
        "\n",
        "**使用方法：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "098c3ea5",
      "metadata": {
        "id": "098c3ea5"
      },
      "outputs": [],
      "source": [
        "# 使用Toolkit\n",
        "result = Toolkit.get_tool(\"browser_snapshot\")()\n",
        "\n",
        "# 直接使用 BrowserTool\n",
        "result = browser.browser_snapshot()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5b189b08",
      "metadata": {
        "id": "5b189b08"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 6: browser_console_messages()\n",
        "\n",
        "检索 JavaScript 控制台消息（日志、警告、错误）以调试 Web 应用程序。\n",
        "\n",
        "**参数：**\n",
        "- 无需参数\n",
        "\n",
        "**示例返回：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "757db189",
      "metadata": {
        "id": "757db189"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"status\": \"success\",\n",
        "    \"console_messages\": [\n",
        "        {\n",
        "            \"level\": \"INFO\",\n",
        "            \"message\": \"Page loaded successfully\",\n",
        "            \"timestamp\": \"2024-01-15T10:30:45.123Z\"\n",
        "        },\n",
        "        {\n",
        "            \"level\": \"WARNING\",\n",
        "            \"message\": \"Deprecated API usage detected\",\n",
        "            \"timestamp\": \"2024-01-15T10:30:46.456Z\"\n",
        "        },\n",
        "        {\n",
        "            \"level\": \"ERROR\",\n",
        "            \"message\": \"Failed to load resource: net::ERR_BLOCKED_BY_CLIENT\",\n",
        "            \"timestamp\": \"2024-01-15T10:30:47.789Z\"\n",
        "        }\n",
        "    ]\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d59a75ea",
      "metadata": {
        "id": "d59a75ea"
      },
      "source": [
        "\n",
        "**使用方法：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "8e8f12fc",
      "metadata": {
        "id": "8e8f12fc"
      },
      "outputs": [],
      "source": [
        "# 使用Toolkit\n",
        "result = Toolkit.get_tool(\"browser_console_messages\")()\n",
        "\n",
        "# 直接使用 BrowserTool\n",
        "result = browser.browser_console_messages()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "eba38948",
      "metadata": {
        "id": "eba38948"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 7: close_browser()\n",
        "\n",
        "关闭浏览器会话并释放系统资源。完成后始终调用此方法。\n",
        "\n",
        "**参数：**\n",
        "- 无需参数\n",
        "\n",
        "**示例返回：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "4f7e21af",
      "metadata": {
        "id": "4f7e21af"
      },
      "outputs": [],
      "source": [
        "{\n",
        "    \"status\": \"success\",\n",
        "    \"message\": \"Browser session closed successfully\"\n",
        "}"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1b79d68e",
      "metadata": {
        "id": "1b79d68e"
      },
      "source": [
        "\n",
        "**使用方法：**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b57b23c3",
      "metadata": {
        "id": "b57b23c3"
      },
      "outputs": [],
      "source": [
        "# 使用Toolkit\n",
        "result = Toolkit.get_tool(\"close_browser\")()\n",
        "\n",
        "# 直接使用 BrowserTool\n",
        "result = browser.close_browser()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8577f126",
      "metadata": {
        "id": "8577f126"
      },
      "source": [
        "\n",
        "#### 5.1.3 元素引用系统\n",
        "\n",
        "浏览器工具使用独特的元素引用系统：\n",
        "\n",
        "1. **元素 ID**：拍摄快照后，交互元素被分配唯一的 ID，如 `e0`、`e1`、`e2` 等。\n",
        "2. **元素引用**：这些 ID 在内部映射到特定的选择器（CSS、XPath、ID 等）\n",
        "3. **交互元素**：只包含可以点击、输入或以其他方式交互的元素\n",
        "4. **元素属性**：每个元素包括描述、目的、标签、类别和可见性信息\n",
        "\n",
        "#### 5.1.4 最佳实践\n",
        "\n",
        "### 设置和初始化\n",
        "- 始终首先调用 `initialize_browser()`\n",
        "- 在服务器环境或后台自动化中使用 `headless=True`\n",
        "- 为加载缓慢的页面设置适当的 `timeout` 值\n",
        "\n",
        "### 元素交互\n",
        "- 在与元素交互之前，始终使用 `navigate_to_url()` 或 `browser_snapshot()` 拍摄快照\n",
        "- 使用快照返回的确切元素 ID（`e0`、`e1` 等）\n",
        "- 提供描述性的 `element` 参数以使交互清晰\n",
        "- 在 `input_text()` 中使用 `submit=True` 进行表单提交\n",
        "\n",
        "### 错误处理和调试\n",
        "- 在进行下一步操作之前检查返回状态\n",
        "- 使用 `browser_console_messages()` 调试 JavaScript 错误\n",
        "- 在页面状态更改后拍摄新快照\n",
        "- 优雅地处理超时错误\n",
        "\n",
        "### 资源管理\n",
        "- 完成后始终调用 `close_browser()`\n",
        "- 每个工具实例只保持一个活动的浏览器会话\n",
        "- 考虑使用上下文管理器进行自动清理\n",
        "\n",
        "#### 5.1.5 完整示例\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "88e39752",
      "metadata": {
        "id": "88e39752"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools import BrowserToolkit\n",
        "\n",
        "# 初始化浏览器工具包\n",
        "Toolkit = BrowserToolkit(browser_type=\"chrome\", headless=False)\n",
        "\n",
        "try:\n",
        "    # 启动浏览器\n",
        "    result = Toolkit.get_tool(\"initialize_browser\")()\n",
        "    print(f\"浏览器初始化: {result['status']}\")\n",
        "\n",
        "    # 导航到页面并获取快照\n",
        "    result = Toolkit.get_tool(\"navigate_to_url\")(url=\"https://example.com\")\n",
        "    print(f\"导航: {result['status']}\")\n",
        "    print(f\"找到 {len(result['interactive_elements'])} 个交互元素\")\n",
        "\n",
        "    # 查找并与元素交互\n",
        "    for element in result['interactive_elements']:\n",
        "        if 'search' in element['purpose'].lower():\n",
        "            # 在搜索字段中输入文本\n",
        "            search_result = Toolkit.get_tool(\"input_text\")(\n",
        "                element=\"搜索字段\",\n",
        "                ref=element['id'],\n",
        "                text=\"python 教程\",\n",
        "                submit=True\n",
        "            )\n",
        "            print(f\"搜索: {search_result['status']}\")\n",
        "            break\n",
        "\n",
        "    # 搜索后拍摄新快照\n",
        "    snapshot = Toolkit.get_tool(\"browser_snapshot\")()\n",
        "    print(f\"新快照: {len(snapshot['interactive_elements'])} 个元素\")\n",
        "\n",
        "    # 检查控制台是否有任何错误\n",
        "    console = Toolkit.get_tool(\"browser_console_messages\")()\n",
        "    if console['console_messages']:\n",
        "        print(f\"控制台消息: {len(console['console_messages'])}\")\n",
        "\n",
        "finally:\n",
        "    # 始终关闭浏览器\n",
        "    Toolkit.get_tool(\"close_browser\")()\n",
        "    print(\"浏览器已关闭\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2fbcdec9",
      "metadata": {
        "id": "2fbcdec9"
      },
      "source": [
        "\n",
        "#### 5.1.6 使用单独的浏览器工具（替代方案）\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "8e1164f1",
      "metadata": {
        "id": "8e1164f1"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools import BrowserTool\n",
        "\n",
        "# 直接初始化浏览器工具\n",
        "browser = BrowserTool(\n",
        "    browser_type=\"chrome\",\n",
        "    headless=False,\n",
        "    timeout=10\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b3c8db74",
      "metadata": {
        "id": "b3c8db74"
      },
      "source": [
        "\n",
        "#### 5.1.7 设置提示\n",
        "\n",
        "- **浏览器要求**:\n",
        "  - Chrome 是默认且最稳定的选项\n",
        "  - 确保您已为 Selenium 安装了 Chrome 或 ChromeDriver\n",
        "  - 对于其他浏览器，安装相应的 WebDriver\n",
        "\n",
        "- **初始化和清理**:\n",
        "  - **始终**首先调用 `initialize_browser()` - 没有它其他方法都不会工作\n",
        "  - 完成后**始终**调用 `close_browser()` 以释放系统资源\n",
        "  - 使用 try-finally 块确保即使出现错误也会进行清理\n",
        "  - 浏览器工具维护内部状态，因此正确的初始化/清理至关重要\n",
        "\n",
        "- **无头模式与可视模式**:\n",
        "  - 设置 `headless=False` 查看浏览器窗口（用于调试和演示）\n",
        "  - 设置 `headless=True` 用于生产或自动化工作流\n",
        "  - 可视模式有助于理解自动化正在做什么\n",
        "\n",
        "- **元素引用和快照**:\n",
        "  - 所有交互都使用快照中的元素 ID，如 \"e0\"、\"e1\"、\"e2\"\n",
        "  - 导航或页面更改后会刷新元素 ID\n",
        "  - 始终使用最新快照的元素引用\n",
        "  - `navigate_to_url()` 方法会自动捕获快照\n",
        "  - 在动态内容更改后使用 `browser_snapshot()` 刷新元素引用\n",
        "\n",
        "- **方法执行顺序**:\n",
        "  ```python\n",
        "  # 必需的工作流模式\n",
        "  browser_Toolkit.get_tool(\"initialize_browser\")()      # 1. 启动浏览器（必需首先）\n",
        "  nav_result = browser_Toolkit.get_tool(\"navigate_to_url\")(url=url)  # 2. 转到页面，获取元素\n",
        "  browser_Toolkit.get_tool(\"input_text\")(ref=\"e0\", text=\"查询\")     # 3. 使用快照中的元素引用\n",
        "  browser_Toolkit.get_tool(\"browser_click\")(ref=\"e1\")               # 4. 使用元素引用点击\n",
        "  browser_Toolkit.get_tool(\"close_browser\")()                       # 5. 清理（必需最后）\n",
        "  ```\n",
        "\n",
        "- **错误处理最佳实践**:\n",
        "  ```python\n",
        "  browser_Toolkit = BrowserToolkit(headless=False)\n",
        "  try:\n",
        "      # 始终检查初始化结果\n",
        "      init_tool = browser_Toolkit.get_tool(\"initialize_browser\")\n",
        "      init_result = init_tool()\n",
        "      if init_result[\"status\"] != \"success\":\n",
        "          raise Exception(\"浏览器初始化失败\")\n",
        "      \n",
        "      # 你的浏览器操作在这里\n",
        "      nav_tool = browser_Toolkit.get_tool(\"navigate_to_url\")\n",
        "      nav_result = nav_tool(url=\"https://example.com\")\n",
        "      # ... 更多操作\n",
        "      \n",
        "  except Exception as e:\n",
        "      print(f\"浏览器操作失败：{e}\")\n",
        "  finally:\n",
        "      # 关键：始终关闭浏览器以释放资源\n",
        "      close_tool = browser_Toolkit.get_tool(\"close_browser\")\n",
        "      close_tool()\n",
        "  ```\n",
        "\n",
        "- **超时和性能**:\n",
        "  - `timeout` 参数控制等待元素加载的时间\n",
        "  - 对于慢速网站或复杂页面增加超时时间\n",
        "  - 使用 `browser_console_messages()` 调试 JavaScript 错误或性能问题\n",
        "\n",
        "---\n",
        "\n",
        "## 6. MCP 工具\n",
        "\n",
        "**模型上下文协议（MCP）工具包提供了一种通过 MCP 协议连接到外部服务的标准化方法。它使代理能够访问专门的工具，如工作搜索服务、数据处理实用程序和其他 MCP 兼容的 API，而无需直接集成每个服务。**\n",
        "\n",
        "### 6.1 MCPToolkit\n",
        "\n",
        "#### 6.1.1 设置\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "1adbb382",
      "metadata": {
        "id": "1adbb382"
      },
      "outputs": [],
      "source": [
        "from evoagentx.tools.mcp import MCPToolkit\n",
        "\n",
        "# 使用配置文件初始化\n",
        "mcp_Toolkit = MCPToolkit(config_path=\"examples/sample_mcp.config\")\n",
        "\n",
        "# 或使用配置字典初始化\n",
        "config = {\n",
        "    \"mcpServers\": {\n",
        "        \"hirebase\": {\n",
        "            \"command\": \"uvx\",\n",
        "            \"args\": [\"hirebase-mcp\"],\n",
        "            \"env\": {\"HIREBASE_API_KEY\": \"your_api_key_here\"}\n",
        "        }\n",
        "    }\n",
        "}\n",
        "mcp_Toolkit = MCPToolkit(config=config)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8759e897",
      "metadata": {
        "id": "8759e897"
      },
      "source": [
        "\n",
        "#### 6.1.2 可用方法\n",
        "\n",
        "`MCPToolkit` 提供以下可调用方法：\n",
        "\n",
        "##### 方法 1: get_tools()\n",
        "\n",
        "**描述**：返回从连接的 MCP 服务器获取的所有可用工具列表。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "0ebfaa63",
      "metadata": {
        "id": "0ebfaa63"
      },
      "outputs": [],
      "source": [
        "# 获取所有可用的 MCP 工具\n",
        "tools = mcp_Toolkit.get_toolkits()\n",
        "\n",
        "# 显示可用工具\n",
        "for i, tool in enumerate(tools):\n",
        "    print(f\"工具 {i+1}: {tool.name}\")\n",
        "    print(f\"描述: {tool.descriptions[0]}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "219c86f8",
      "metadata": {
        "id": "219c86f8"
      },
      "source": [
        "\n",
        "**返回类型**：`List[Tool]`**示例返回**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "6a378d6b",
      "metadata": {
        "id": "6a378d6b"
      },
      "outputs": [],
      "source": [
        "[MCPTool(name=\"HirebaseSearch\", descriptions=[\"通过提供关键词搜索工作信息\"]),\n",
        " MCPTool(name=\"HirebaseAnalyze\", descriptions=[\"分析给定技能的工作市场趋势\"])]"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9d505d09",
      "metadata": {
        "id": "9d505d09"
      },
      "source": [
        "\n",
        "---\n",
        "\n",
        "##### 方法 2: disconnect()\n",
        "\n",
        "**描述**：断开与所有 MCP 服务器的连接并清理资源。\n",
        "\n",
        "**使用示例**："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "ea253cfa",
      "metadata": {
        "id": "ea253cfa"
      },
      "outputs": [],
      "source": [
        "# 使用完 MCP 工具包后\n",
        "mcp_Toolkit.disconnect()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "66c410b3",
      "metadata": {
        "id": "66c410b3"
      },
      "source": [
        "\n",
        "**返回类型**：`None`\n",
        "\n",
        "#### 6.1.3 使用 MCP 工具\n",
        "\n",
        "一旦从 MCPToolkit 获取了工具，你可以像使用任何其他 EvoAgentX 工具一样使用它们：\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "ea533597",
      "metadata": {
        "id": "ea533597"
      },
      "outputs": [],
      "source": [
        "# 从工具包获取所有工具\n",
        "tools = mcp_Toolkit.get_toolkits()\n",
        "\n",
        "# 查找特定工具\n",
        "hirebase_tool = None\n",
        "for tool in tools:\n",
        "    if \"hire\" in tool.name.lower() or \"search\" in tool.name.lower():\n",
        "        hirebase_tool = tool\n",
        "        break\n",
        "\n",
        "if hirebase_tool:\n",
        "    # 使用工具搜索信息\n",
        "    search_query = \"data scientist\"\n",
        "    result = hirebase_tool.tools[0](**{\"query\": search_query})\n",
        "\n",
        "    print(f\"'{search_query}' 的搜索结果：\")\n",
        "    print(result)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "bac2eadb",
      "metadata": {
        "id": "bac2eadb"
      },
      "source": [
        "\n",
        "#### 6.1.4 设置提示\n",
        "\n",
        "- **配置文件**：配置文件应遵循 MCP 协议的服务器配置格式：\n",
        "  ```json\n",
        "  {\n",
        "      \"mcpServers\": {\n",
        "          \"serverName\": {\n",
        "              \"command\": \"executable_command\",\n",
        "              \"args\": [\"command_arguments\"],\n",
        "              \"env\": {\"ENV_VAR_NAME\": \"value\"}\n",
        "          }\n",
        "      }\n",
        "  }\n",
        "  ```\n",
        "\n",
        "- **服务器类型**：\n",
        "  - **基于命令的服务器**：使用 `command` 字段指定可执行文件\n",
        "  - **基于 URL 的服务器**：使用 `url` 字段指定服务器端点\n",
        "\n",
        "- **连接管理**：\n",
        "  - 使用完 MCPToolkit 后始终调用 `disconnect()` 以释放资源\n",
        "  - 使用 try-finally 块进行自动清理：\n",
        "    ```python\n",
        "    try:\n",
        "        Toolkit = MCPToolkit(config_path=\"config.json\")\n",
        "        tools = Toolkit.get_toolkits()\n",
        "        # 在这里使用工具\n",
        "    finally:\n",
        "        Toolkit.disconnect()\n",
        "    ```\n",
        "\n",
        "- **错误处理**：\n",
        "  - 如果无法连接到服务器，MCPToolkit 将记录警告消息\n",
        "  - 最好在工具调用周围实现错误处理：\n",
        "    ```python\n",
        "    try:\n",
        "        result = tool.tools[0](**{\"query\": \"example query\"})\n",
        "    except Exception as e:\n",
        "        print(f\"调用 MCP 工具时出错：{str(e)}\")\n",
        "    ```\n",
        "\n",
        "- **环境变量**：\n",
        "  - API 密钥和其他敏感信息可以通过配置中的环境变量提供\n",
        "  - 你也可以在运行应用程序之前在环境中设置它们\n",
        "\n",
        "---\n",
        "\n",
        "## 总结\n",
        "\n",
        "在本教程中，我们探索了 EvoAgentX 中的工具生态系统：\n",
        "\n",
        "1. **工具架构**：理解了基础 Tool 类及其标准化接口\n",
        "2. **代码解释器**：学习了如何使用 Python 和 Docker 解释器安全执行 Python 代码\n",
        "3. **搜索工具**：发现了如何使用 Wikipedia 和 Google 搜索工具访问网络信息\n",
        "4. **文件操作**：了解了如何处理文件操作，包括读取和写入文件，并特别支持不同的文件格式，如 PDF\n",
        "5. **浏览器自动化**：学习了如何控制网页浏览器与网站和 Web 应用程序交互\n",
        "6. **MCP 工具**：学习了如何使用模型上下文协议连接到外部服务\n",
        "\n",
        "EvoAgentX 中的工具通过提供对外部资源和计算的访问来扩展你的代理功能。通过将这些工具与代理和工作流结合，你可以构建强大的 AI 系统，能够检索信息、执行计算并与世界交互。\n",
        "\n",
        "有关更高级的用法和自定义选项，请参考 [API 文档](../api/tools.md) 并探索仓库中的示例。\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": [],
      "include_colab_link": true
    },
    "language_info": {
      "name": "python"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}